<?php
// +----------------------------------------------------------------------
// | SentCMS [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2024 http://www.tensent.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: molong <molong@tensent.cn> <http://www.tensent.cn>
// +----------------------------------------------------------------------
namespace Modules\Auth\Services;

use Modules\Auth\Models\Admin;

class UsersService {

	/**
	 * @title 获取用户列表
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function getDataList($request) {
		$map = [];

		if ($request->filled('username')) {
			$map[] = ['username', 'like', '%' . $request->input('username') . '%'];
		}
		if ($request->filled('mobile')) {
			$map[] = ['mobile', 'like', '%' . $request->input('mobile') . '%'];
		}
		if ($request->filled('email')) {
			$map[] = ['email', 'like', '%' . $request->input('email') . '%'];
		}
		if ($request->filled('department_id')) {
			$map[] = ['department_id', '=', $request->input('department_id')];
		}

		$query = Admin::where($map)->orderBy('uid', 'desc');

		$data = [
			'total' => $query->count(),
			'page' => $request->input('page', 1),
			'data' => $query->offset($request->input('offset', 0))->limit($request->input('limit', 10))->get(),
		];
		return $data;
	}

	/**
	 * @title 添加用户
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function create($request) {
		$request->validate([
			'username' => 'required|unique:auth_admins,username',
			// 'email' => 'required|unique:auth_admins',
			// 'mobile' => 'required|unique:auth_admins',
			'password' => 'required|min:8',
		]);

		$data = $request->all();
		$data['status'] = 1;
		$data['last_login_at'] = date('Y-m-d H:i:s');
		$data['last_login_ip'] = $request->ip();

		$admins = Admin::create($data);
		$request->whenFilled('roles_id', function ($value) use ($admins) {
			$admins->roles()->sync($value);
		});
		return $admins;
	}

	/**
	 * @title 修改用户
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function update($request) {
		$request->validate([
			'username' => 'required|unique:auth_admins,username,' . $request->input('uid').',uid',
		]);
		try {
			$admins = Admin::findOrFail($request->input('uid'));
		} catch (\Throwable $th) {
			throw new \Exception("用户不存在！", 1);
		}

		if ($request->filled('username')) {
			$admins->username = $request->input('username');
		}
		if ($request->filled('email')) {
			$admins->email = $request->input('email');
		}
		if ($request->filled('mobile')) {
			$admins->mobile = $request->input('mobile');
		}
		if ($request->filled('nickname')) {
			$admins->nickname = $request->input('nickname');
		}
		if ($request->filled('department_id')) {
			$admins->department_id = $request->input('department_id');
		}
		if ($request->filled('avatar')) {
			$admins->avatar = $request->input('avatar');
		}
		if ($request->filled('remark')) {
			$admins->remark = $request->input('remark');
		}
		if ($request->filled('status')) {
			$admins->status = $request->input('status');
		}
		if ($request->filled('password')) {
			$admins->password = $request->input('password');
		}
		$request->whenFilled('roles_id', function ($value) use ($admins) {
			$admins->roles()->sync($value);
		});

		$admins->save();
		return $admins;
	}

	/**
	 * @title 删除用户
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function delete($request) {
		if($request->filled('id')){
			if($request->input('id') == env('ADMIN_ID', 1)){
				throw new \Exception("超级管理员不能删除！", 1);
			}
			try {
				$admins = Admin::findOrFail($request->input('id'));
			} catch (\Throwable $th) {
				throw new \Exception("角色不存在！", 1);
			}
			$admins->roles()->detach();
			$admins->delete();
		}
		if($request->filled('ids')){
			if(in_array(env('ADMIN_ID', 1), $request->input('ids'))){
				throw new \Exception("超级管理员不能删除！", 1);
			}
			try {
				$admins = Admin::whereIn('uid', $request->input('ids'));
				foreach ($admins->get() as $item) {
					$item->roles()->detach();   //删除关联
				}
				$admins = $admins->delete();
			} catch (\Throwable $th) {
				throw new \Exception($th->getMessage(), 1);
			}
		}
		return $admins;
	}

	/**
	 * @title 修改密码
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function upPassword($request) {
		try {
			$admins = Admin::findOrFail($request->input('uid'));
		} catch (\Throwable $th) {
			throw new \Exception("用户不存在！", 1);
		}

		$admins->password = $request->input('password');
		$admins->save();
		return $admins;
	}

	/**
	 * @title 设置角色
	 *
	 * @param [type] $request
	 * @return void
	 */
	public function uprole($request){
		try {
			$admins = Admin::with(['roles'])->findOrFail($request->input('uid'));
		} catch (\Illuminate\Database\Eloquent\ModelNotFoundException $th) {
			throw new \Exception($th->getMessage(), 1);
		}

		$admins->roles()->sync($request->input('roles'));
		return $admins;
	}
}
